package com.globallogic.training.javase.tdd;

public class Node {

	private String value;
	private Node leftChild;
	private Node rightChild;
	
	public Node(String value) {
		if (value == null) {
			throw new IllegalArgumentException(
					"Node value argument is null.");
		}
		if (value.isEmpty()) {
			throw new IllegalArgumentException(
					"Node value argument is empty.");
		}
		
		this.value = value;
	}
	
	public Node getLeftChild() {
		return leftChild;
	}

	public Node getRightChild() {
		return rightChild;
	}
	
	public int getHeight() {
		int depth = 1;
		
		if (isLeaf()) {
			return 0;
		} else if(leftChild == null) {
			depth += rightChild.getHeight();
		} else if(rightChild == null) {
			depth += leftChild.getHeight();
		} else {
			depth += Math.max(leftChild.getHeight(), rightChild.getHeight());
		}
		
		return depth;
	}

	public void addNode(String newValue) {
		if (value.compareTo(newValue) > 0) {
			if (leftChild == null) {
				leftChild = new Node(newValue);
			} else {
				leftChild.addNode(newValue);
			}
		}
		
		if (value.compareTo(newValue) < 0) {
			if (rightChild == null) {
				rightChild = new Node(newValue);
			} else {
				rightChild.addNode(newValue);
			}
		}
	}

	public boolean isLeaf() {
		if (leftChild == null && rightChild == null) {
			return true;
		}
		return false;
	}
	
	@Override
	public String toString() {
		if (isLeaf()) {
			return value;
		} else if(leftChild == null) {
			return value + "(," + rightChild + ")"; 
		} else if(rightChild == null) {
			return value + "(" + leftChild + ",)"; 
		} else {
			return value + "(" + leftChild + "," + rightChild + ")";
		}
	}
	
}
